package com.situ.shop.controller;

import com.octo.captcha.Captcha;
import com.octo.captcha.engine.CaptchaEngine;
import com.situ.shop.CapchaHelper;
import com.situ.shop.Constants;
import com.situ.shop.dao.MainMapper;
import com.situ.shop.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by Young on 2016/7/21.
 */
@Controller //表示这个类是一个Controller，于是当请求路径 / 时，这个Contrller的实例被自动创建
@RequestMapping("/") //这个controller对应到路径 /
public class MainController {
    @Autowired
    public MainMapper mainMapper;
    //指定这个方法映射到哪个地址，这里没写地址，它会映射到类的地址。
    @RequestMapping(method = RequestMethod.GET)
    public String index(HttpSession session, Model model){
        return "index";
    }
    //注册按钮响应事件
    @RequestMapping(value = "toRegister")
    public String toRegister(){
        return "regist";
    }
    @RequestMapping(value = "payment")
    public String toPayment(){
        return "payment";
    }
    @RequestMapping(value = "/toLogin")
    public String toLogin(){
        return "login";
    }
    //注册用户
    @RequestMapping(value = "register")
    public String register(HttpSession session,
                           Model model,
                           @RequestParam("username") String username,
                           @RequestParam("password") String password,
                           @RequestParam("email") String email,
                           @RequestParam("name") String name,
                           @RequestParam("sex") String sex,
                           @RequestParam("phone")String phone,
                           @RequestParam("address") String address){
        User user=new User(0,username,password,email,name,sex,phone,address);
        mainMapper.addOneNewUser(user);
        return "redirect:/";
    }

    @RequestMapping(value="login" )
        public String login(HttpSession session,Model model,
                            @RequestParam("username")String username,
                            @RequestParam("password") String password,
                            @RequestParam("captcha") String token){
        //存放错误提示
        String errMsg = "";
        int loginID = 0;

        //登录，需要验证验证码
        Captcha captcha= (Captcha) session.getAttribute("captcha");
        if(!captcha.validateResponse(token)) {
            //验证码错误！
            errMsg = "验证码错误";
            model.addAttribute("value_name", username);
            model.addAttribute("value_password", password);
            model.addAttribute("errMsg", errMsg);
            return "login"; //返回前台文件件的名字。
        }
        //验证码正确，继续验证登录
        try {
            User user = mainMapper.login(username, password);
            session.setAttribute(Constants.USER_LOGIN_ATTR_ID, user.getId());
            session.setAttribute(Constants.USER_LOGIN_ATTR_NAME, user.getName());
            //登录成功 重定向到主页面
            return "redirect:login";
        }catch (Exception e){
            //如果失败的话，我们要：
            // 1 继续显示登录页面
            // 2 需要在输入框中显示提交之前输入的用户名和密码
            // 3 显示错误信息
            errMsg = "用户名或密码不存在";
            //放到model中的数据可以在jsp中直接使用
            model.addAttribute("value_name", username);
            model.addAttribute("value_password", password);
            model.addAttribute("errMsg", errMsg);
            return "login";
        }

    }
    //向客户端返回验证码图片的路径
    @RequestMapping("/captcha_img")
    public @ResponseBody
    byte[] getCaptchaImgData(HttpSession session) throws IOException {
        //产生验证码图片

        //获取验证码背景图片的路径，这路径放了很多作为背景的图像
        String captcha_backgrounds = session.getServletContext().getRealPath("/WEB-INF/img/captcha");
        CaptchaEngine ce = CapchaHelper.getCaptchaEngine(captcha_backgrounds);
        //需要admin网页中用js定时从服务端获取当前的验证码
        Captcha captcha = ce.getNextCaptcha();
        //为了验证，把captcha对象放到session中，以在客户端提交验证码时进行验证
        session.setAttribute("captcha", captcha);
        //获取验证码图片，这是未压缩的位图
        BufferedImage image = (BufferedImage) captcha.getChallenge();
        ByteArrayOutputStream bao=new ByteArrayOutputStream();
        //应缩成jpg并写到输出流中
        ImageIO.write(image, "jpg", bao);
        return bao.toByteArray();
    }
    @RequestMapping(value = "addToCart")
    public String addToCart(){
        return "shop_cart";
    }

    @RequestMapping(value = "myInfo")
    public String tot(){
        return "my_info";
    }
}
